const { src, dest, parallel, series, watch } = require('gulp')
const del = require('del')
const gulp = require('gulp')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()

const browserSync = require('browser-sync') // web开发服务器, 创建完成后，会自动打开浏览器localhost:3000
const bs = browserSync.create()
// const { notify } = require('browser-sync')
const data ={
  menus: [{
    name: 'Home',
    icon: '',
    link: 'index.html'
  },{
    name: 'About',
    icon: '',
    link: 'about.html'
  }],
  pkg: require('./package.json'),
  date: new Date()
}

const scss = () => {
  return src('src/assets/styles/*.scss', {base: 'src'})
    .pipe(plugins.sass())
    .pipe(dest('dist'))
    .pipe(bs.reload({stream:true}))
}
const script = () => {
  return src('src/assets/script/*.js', {base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(plugins.uglify())
    .pipe(dest('dist'))
    .pipe(bs.reload({stream:true}))
}
const pages = () => {
  return src('src/*.html', {base:'src'})
    .pipe(plugins.swig({data}))
    .pipe(dest('dist'))
    .pipe(bs.reload({stream:true}))
}
// 图片压缩
const images = () => {
  return src('src/assets/images/**', {base: 'src'})
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
// 字体文件处理
const font = () => {
  return src('src/assets/font/**')
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
// 将不需要构建的文件直接拷贝至构建后的文件夹下
const extra = () => {
  return src('public/**', {base: 'public'})
    .pipe(dest('dist'))
}
// 
const useref = () => {
  return src('dist/*.html', {base:'dist'})
    .pipe(plugins.useref({ searchPath:['dist','.'] }))
    .pipe(dest('dist'))
}
// 在构建之前将dist文件夹下清除
const clean = () => {
  return del(['dist'])
}
// 本地服务器
// 使用watch 监听 src下的文件，变动后执行相应的任务，编译到dist后，browserSync会监听到dist下文件的变化，从而更新到浏览器
const serve = () => {
  watch('src/assets/styles/*.scss', scss)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', pages)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ],bs.reload)
  bs.init({
    notify: false, // 页面启动时右上角的小提示框是否显示
    port: '2020', // 端口号 默认3000
    // files: 'dist/**', // 服务器启运后，**需要监听的文件路径通配符。
    server:{
      baseDir: ['dist','src','public'],
      routes: { // 路径替换
        '/node_modules': 'node_modules'
      }
    }
  })
}
const compile = parallel(scss, script, pages)
// build 上线前执行的任务
const build = series(clean, parallel(series(compile, useref), images, font,extra)) //parallel(compile,extra)
// dev 测试阶段执行的任务
const dev = series(clean, compile, serve)
module.exports = {
  build,
  dev,
  clean,
}

